package com.example.consumptionrecords.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 多Realm认证
 * hhzr9
 * 2024 \ 04 \ 01
 */

public class ModularRealmAuthenticator extends org.apache.shiro.authc.pam.ModularRealmAuthenticator {

	@Override
	protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// 判断getRealms()是否返回为空
		assertRealmsConfigured();
		// 所有Realm
		Collection<Realm> realms = getRealms();
		// 登录类型对应的所有Realm
		Realm typeRealms = null;
		if (authenticationToken instanceof PhoneAuthCodeToken) {
			typeRealms = new ArrayList<Realm>(realms).stream().filter(realm -> realm instanceof PhoneRealm).findFirst().orElse(null);
		}
		if (authenticationToken instanceof UsernamePasswordToken) {
			typeRealms = new ArrayList<Realm>(realms).stream().filter(realm -> realm instanceof UserRealm).findFirst().orElse(null);
		}
		return doSingleRealmAuthentication(typeRealms, authenticationToken);
	}
}
